package com.example.files;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;

/**
 * 读取文件测试类
 * @author wanghongyu02
 * @date 2024-08-13 16:29
 */
@Slf4j
public class FileTest {

    public static void main(String[] args) {

        // 1. ClassPathResource可以拿到resource文件夹下的文件
        log.info("########1########");
        Resource resource = new ClassPathResource("files/test.txt");
        try {
            // 获取文件的输入流
            InputStream inputStream = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            // 逐行读取文件内容并打印
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 关闭BufferedReader
            reader.close();
        } catch (IOException e) {
            // 捕获并打印异常
            e.printStackTrace();
        }

        // 2. 获取项目根目录
        log.info("########2########");
        String projectDir = System.getProperty("user.dir");
        System.out.println("项目根目录：" + projectDir);

        // 创建文件对象，指向项目根目录下的 files/test.txt
        File file = new File(projectDir + "/flink/words.txt");

        // 检查文件是否存在
        if (file.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件不存在: " + file.getAbsolutePath());
        }
    }
}
